package net.zypro.sample.net;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import net.zypro.sample.C;
import net.zypro.sample.model.ErrorMessage;

import java.io.UnsupportedEncodingException;

/**
 * Created by mac on 15/5/18.
 */
public abstract class NetErrorListener implements Response.ErrorListener {

    public abstract void onError(ErrorMessage msg);

    @Override
    public void onErrorResponse(VolleyError error) {
        ErrorMessage msg=null;

        if(error==null)
        {
            msg=new ErrorMessage(C.ErrorCode.CLIENT_UNKNOWN_ERROR);
        }else{
           NetworkResponse response=error.networkResponse;

           if(response!=null)
           {
               Gson gson=new Gson();

               try {
                   String json = new String(
                           response.data,
                           HttpHeaderParser.parseCharset(response.headers));
                   msg=gson.fromJson(json, ErrorMessage.class);
               } catch (UnsupportedEncodingException e) {
                   msg=new ErrorMessage(C.ErrorCode.CLIENT_UNKNOWN_ERROR);
               } catch (JsonSyntaxException e) {
                   msg=new ErrorMessage(C.ErrorCode.CLIENT_JSON_ERROR);
               }
           }else{
               msg=new ErrorMessage(C.ErrorCode.CLIENT_UNKNOWN_ERROR);
           }
        }

        onError(msg);
    }
}
